<template>
	<view class="container">
		<!-- 文件上传 -->
		<view class="file-upload" style="margin-bottom: 30px;">
			<uni-section title="选择任意文件" type="line">
				<view class="example-body">
					<uni-file-picker limit="5" file-mediatype="all" title="最多选择5个文件" @select="handleSelectFiles"
						@change="handleChange" />
				</view>
			</uni-section>


			<button type="primary" size="default" @click="uploadFiles" style="margin-top: 50px;">上传</button>
		</view>

		<!-- 搜索表单 -->
		<view class="query-content" style="margin-bottom: 30px;">
			<uni-forms ref="queryFormRef" :model="queryForm" :rules="rules" class="form-view">
				<view class="form-row">
					<uni-forms-item label="" name="fileName" class="form-item" required>
						<uni-easyinput v-model="queryForm.fileName" placeholder="请输入文件名称" trim="true"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="" name="fileId" class="form-item">
						<button type="primary" size="mini" @click="submitForm">查 询</button>
					</uni-forms-item>

				</view>
			</uni-forms>

		</view>

		<!-- 文件列表 -->
		<view class="uni-container">
			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="handleSelectionChange">
				<uni-tr>
					<uni-th width="150" align="center">文件名</uni-th>
					<uni-th width="185" align="center">设 置</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in paginatedFileList" :key="index" :data-file-id="item.fileId">
					<uni-td>{{ item.fileName }}</uni-td>
					<uni-td>
						<view class="uni-group" align="center">
							<button class="uni-button" size="mini" type="primary"
								@tap="downloadFileById(item.fileId)">下载</button>
							<button class="uni-button" size="mini" type="warn"
								@tap="showFileDetail(item.fileId)">详情</button>
							<button class="uni-button" size="mini" type="primary"
								@tap="fileRoleEdit(item.fileId)">权限</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
			<view class="uni-pagination-box">
				<uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
					@change="change" />
			</view>
			<!-- 新增批量删除按钮 -->
			<button type="warn" size="mini" @click="batchDelete">批量删除</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import fileApi from '@/api/file.js';
	import classesApi from '@/api/class.js'
	
	
	const classList = ref([]);
	onMounted(() => {
		// 在页面挂载时获取班级列表数据
		console.log('----Onload');
		fileApi.getFileList().then(apiRes => {
			if (apiRes.code === 200) {
				console.log('获取文件列表成功', apiRes);
				fileList.value = apiRes.data;
				total.value = apiRes.data.length;
				// 重置当前页码为1，因为获取了新的文件列表
				pageCurrent.value = 1;
			}
		});
		classesApi.getClassList().then(res => {

			console.log('班级列表数据：', res.data);
			const classData = res.data.map(item => ({
				value: item.classesId, // 假设班级数据中班级编号的字段为id，根据实际情况修改
				text: item.classesName // 假设班级数据中班级名称的字段为name，根据实际情况修改
			}));
			classList.value = classData;
		}).catch(err => {
			console.log('获取班级列表出错：', err);
		});
	})

	const rules = {
		fileName: {
			rules: [{
				required: true,
				errorMessage: '请输入文件名称',
			}, ],
		},
	};
	const queryForm = ref({
		fileName: '',
	});
	const queryFormRef = ref(null);

	const fileList = ref([]); // 初始化文件列表
	const pageSize = ref(10);
	const pageCurrent = ref(1);
	const total = ref(0);
	const loading = ref(false);

	const paginatedFileList = computed(() => {
		const start = (pageCurrent.value - 1) * pageSize.value;
		const end = start + pageSize.value;
		return fileList.value.slice(start, end);
	});
	

	// 文件列表查询与文件文件ID查询文件信息
	const submitForm = () => {
		queryFormRef.value.validate().then(res => {
			if (res) {
				console.log('表单验证通过', queryForm.value);
				fileApi.getFileList(queryForm.value.fileName).then(apiRes => {
					if (apiRes.code === 200) {
						console.log('获取文件列表成功', apiRes);
						fileList.value = apiRes.data;
						total.value = apiRes.data.length;
						// 重置当前页码为1，因为获取了新的文件列表
						pageCurrent.value = 1;
					}
				});
			}
		}).catch(err => {
			console.error('表单验证失败', err);
		});
	};

	// 文件上传相关
	const selectedFiles = ref([]);
	const range = ref(0); // 默认为0，全部可见，根据实际情况修改

	const formData = ref({
		files: [],
		userName: '',
		range: '',
	});

	const handleSelectFiles = (e) => {
		selectedFiles.value = e.tempFiles;
	};

	const radioChange = (value) => {
		// 确保这里正确地更新了 range 的值
		range.value = value;
	};
	console.log("range.value------>", range.value)

	const uploadFiles = () => {
		if (selectedFiles.value.length === 0) {
			uni.showToast({
				title: '请选择文件',
				icon: 'none',
			});
			return;
		}

		// 从本地存储获取用户信息
		const userInfo = uni.getStorageSync('userInfo');
		const username = userInfo.userName;
		const pathUrl = uni.getStorageSync('upload');


		const uploadTasks = selectedFiles.value.map((file) => {
			return new Promise((resolve, reject) => {
				uni.uploadFile({

					url: pathUrl,
					filePath: file.path,
					name: 'files',
					formData: {
						username: username,
						range: 0
					},
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						reject(err);
					},
				});
			});
		});

		Promise.all(uploadTasks).then((responses) => {
			console.log('所有文件上传成功:', responses);
			uni.showToast({
				title: '文件上传成功!',
				icon: 'success',
			});
			// 新增：文件上传成功后，清空选择文件记录
			selectedFiles.value = [];
		}).catch((error) => {
			console.error('Error uploading files:', error);
			uni.showToast({
				title: '文件上传失败：' + (error.message || '未知错误'),
				icon: 'none',
			});
		});
	};

	// 根据文件id删除文件
	const deleteFileById = (fileId) => {
		console.log("要删除的文件的id--->", fileId);
		uni.showModal({
			title: '确认删除',
			content: '您确定要删除这个文件吗？',
			success: function(res) {
				if (res.confirm) {
					// 用户点击了确认，执行删除操作
					fileApi.deleteFileByFileId(fileId).then(apiRes => {
						if (apiRes.code === 200) {
							uni.showToast({
								title: '文件删除成功!',
								icon: 'success',
							});
							// 从fileList中移除被删除的文件
							const index = fileList.value.findIndex(item => item.fileId === fileId);
							if (index !== -1) {
								fileList.value.splice(index, 1);
								// 如果当前页是最后一页且这一页只有一个文件，需要调整pageCurrent
								if (pageCurrent.value === Math.ceil(fileList.value.length /
										pageSize.value) && fileList.value.length % pageSize
									.value === 0 && pageCurrent.value > 1) {
									pageCurrent.value--;
								}
							}
							// 重新获取文件列表以刷新页面
							total.value = fileList.value.length;
							return;
						} else {
							uni.showToast({
								title: '文件删除失败：' + (apiRes.message || '未知错误'),
								icon: 'none',
							});
							return;
						}
					}).catch(err => {
						console.error('文件删除错误', err);
						uni.showToast({
							title: '文件删除失败，请检查网络或联系管理员',
							icon: 'none',
						});
					});
				} else if (res.cancel) {
					// 用户点击了取消，不做任何操作
					console.log('用户点击取消');
				}
			}
		});
	};

	// 新增批量删除相关逻辑
	const selectedFileIds = ref([]);
	// 新增批量删除相关逻辑
	const handleSelectionChange = (e) => {
		const selectedIndexes = e.detail.index;
		console.log("selectedIndexes--->", selectedIndexes);
		// 拿到勾选数据的id放到selectedFileIds.value中
		selectedFileIds.value = selectedIndexes.map(index => fileList.value[index].fileId);
	};

	const batchDelete = () => {
		console.log("selectedFileIds.value---->", selectedFileIds.value)
		uni.showModal({
			title: '确认批量删除',
			content: '您确定要删除选中的文件吗？',
			success: function(res) {
				if (res.confirm) {
					fileApi.deleteFileByFileIdList(selectedFileIds.value).then(apiRes => {
						if (apiRes.code === 200) {
							uni.showToast({
								title: '批量删除成功!',
								icon: 'success',
							});
							// 从fileList中移除被删除的文件
							selectedFileIds.value.forEach(fileId => {
								const index = fileList.value.findIndex(item => item
									.fileId === fileId);
								if (index !== -1) {
									fileList.value.splice(index, 1);
								}
							});
							// 根据情况调整pageCurrent
							if (pageCurrent.value === Math.ceil(fileList.value.length / pageSize
									.value) && pageCurrent.value > 1) {
								pageCurrent.value--;
							}
							total.value = fileList.value.length;
						} else {
							uni.showToast({
								title: '批量删除失败：' + (apiRes.message || '未知错误'),
								icon: 'none',
							});
						}
					})
				} else if (res.cancel) {
					// 用户点击了取消，不做任何操作
					console.log('用户点击取消');
				}
			}
		});
	};

	const downloadFileById = (fileId) => {
		// 根据文件 ID 从后端获取文件下载链接
		const pathUrl = uni.getStorageSync('download');
		console.log("文件下载----->");
		uni.downloadFile({
			url: `${pathUrl}&fileId=${fileId}`,
			success: (downloadRes) => {
				console.log("downloadRes---->", downloadRes);
				if (downloadRes.statusCode === 200) {
					// 尝试保存文件，虽然不能指定具体位置，但可以提示用户可能的位置
					uni.saveFile({
						tempFilePath: downloadRes.tempFilePath,
						success: function(data) {
							const savedFilePath = data.savedFilePath;
							uni.showToast({
								title: '文件下载成功！可能保存在手机的下载文件夹或文件管理器中。',
								icon: 'success'
							});
							console.log("savedFilePath---->", savedFilePath);
							// 获取文件扩展名，假设文件路径中包含扩展名
							const fileExtension = savedFilePath.split('.').pop();
							if (['png', 'jpg', 'jpeg'].includes(fileExtension)) {
								uni.previewImage({
									urls: [savedFilePath],
									current: savedFilePath
								});
							}
							return;
							// else if (fileExtension === 'pdf') {
							// 	uni.navigateTo({
							// 		url: `/pages/pdf-preview?filePath=${encodeURIComponent(savedFilePath)}`
							// 	});
							// } 
							// else {
							// 	uni.showToast({
							// 		title: '不支持的文件类型预览',
							// 		icon: 'none'
							// 	});
							// }
						},
						fail: function(err) {
							uni.showToast({
								title: '文件保存失败：' + (err.message || '未知错误'),
								icon: 'none'
							});
						}
					});
				} else {
					uni.showToast({
						title: '文件下载失败：' + (downloadRes.message || '未知错误'),
						icon: 'none'
					});
				}
			},
			fail: (downloadErr) => {
				uni.showToast({
					title: '文件下载失败：' + (downloadErr.message || '未知错误'),
					icon: 'none'
				});
			}
		});
	};
</script>

<style lang="scss">
	.container {
		padding: 30px;
	}

	.form-view {
		display: flex;
		flex-direction: column;
		align-items: stretch;
	}

	.form-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
	}

	.form-item {
		flex: 1;
		margin-right: 10px;

		&:last-child {
			margin-right: 0;
		}
	}

	.button-round {
		border-radius: 999px; // Example for rounded button
	}

	.contacts-list {
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		margin-top: 20px;
		padding: 10px;
	}

	.contact-item {
		display: flex; // 设置为flex布局，使子元素并排显示
		border-bottom: 1px solid #eee;
		padding: 10px 0;

		&:last-child {
			border-bottom: none;
		}
	}

	.contact-cell {
		flex: 1; // 每个单元格占据相同的空间
		text-align: center;
		padding: 10px; // 增加内边距，以便单元格之间有间隔
	}

	.contact-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 5px;
	}

	.contact-name {
		font-size: 18px;
		font-weight: bold;
	}

	.contact-sex {
		font-size: 16px;
	}

	.contact-details {
		display: flex;
		justify-content: space-between;
		font-size: 14px;
	}

	.contact-phone,
	.contact-email,
	.contact-class {
		margin-right: 10px;

		&:last-child {
			margin-right: 0;
		}
	}

	.table-header {
		display: flex;
		background-color: #f0f0f0;
		padding: 10px;
		font-weight: bold;
	}

	.header-cell {
		flex: 1;
		text-align: center;
	}

	.pagination {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}

	button {
		margin: 0 10px;
	}

	.file-item {
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 10px 0;

		&:last-child {
			border-bottom: none;
		}
	}

	.file-cell {
		flex: 1;
		text-align: center;
		padding: 10px;
	}

	.delete-button {
		margin-left: 10px;
		background-color: #f44336; // 红色背景
		color: white;
		border: none;
		border-radius: 4px;
		padding: 5px 10px;
		cursor: pointer;
		transition: background-color 0.3s ease;

		&:hover {
			background-color: darken(#f44336, 10%);
		}
	}

	.batch-delete {
		margin-top: 20px;
		text-align: center;
	}

	.example-body {
		padding: 10px;
		padding-top: 0;
	}

	.custom-image-box {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.text {
		font-size: 14px;
		color: #333;
	}

	.uni-group {
		display: flex;
		align-items: center;
	}

	.text {
		font-size: 12px;
		color: #666;
		margin-top: 5px;
	}

	.uni-px-5 {
		padding-left: 10px;
		padding-right: 10px;
	}

	.uni-pb-5 {
		padding-bottom: 10px;
	}
</style>